package com.aruba.mvvmapplication.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.aruba.mvvmapplication.adapter.FooterAdapter
import com.aruba.mvvmapplication.adapter.MoviePagingAdapter
import com.aruba.mvvmapplication.databinding.ActivityMainBinding
import com.aruba.mvvmapplication.extension.setPagingAdapter
import com.aruba.mvvmapplication.viewmodel.MovieViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
    private val viewModel: MovieViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        val adapter = MoviePagingAdapter()

        binding.recyclerview.adapter = adapter
            .run { withLoadStateFooter(FooterAdapter(this)) }

        lifecycleScope.launchWhenCreated {
            //监听adapter状态
            adapter.loadStateFlow.collect {
                //根据刷新状态来通知swiprefreshLayout是否刷新完毕
                binding.refreshLayout.isRefreshing = it.refresh is LoadState.Loading
            }
        }

        binding.recyclerview.setPagingAdapter(
            owner = this,
            adapter = adapter,
            liveData = viewModel.data
        ) {
            binding.refreshLayout.isEnabled = false
        }
    }
}